package com.cqan.security;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

import com.cqan.orm.PropertyFilter;
import com.cqan.system.entity.SystemEntity;
import com.cqan.system.service.SystemService;
import com.google.common.collect.Lists;

/**
 * @author slaton
 * 
 *         下午05:12:29
 */
public class FilterSecurityInterceptor extends AbstractSecurityInterceptor
		implements Filter {

	private static final Logger logger = LoggerFactory.getLogger("ds.debug");
	
	private boolean initFlag;
	
	private Map<String,String> globalMap = new ConcurrentHashMap<String, String>();
	
	private FilterInvocationSecurityMetadataSource securityMetadataSource;

	private SystemService systemService;
	
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if (!initFlag) {
			initSystem();
			initFlag = true;
		}
		HttpSession session = ((HttpServletRequest)request).getSession();
		Boolean inited =  (Boolean) session.getAttribute("inited");
		if (inited==null||!inited) {
			Set<Entry<String, String>> entrys = globalMap.entrySet();
			for (Iterator<Entry<String, String>> it = entrys.iterator(); it.hasNext();) {
				Entry<String, String> entry = it.next();
				session.setAttribute(entry.getKey(), entry.getValue());
			}
			session.setAttribute("inited", true);
		}
		if (logger.isDebugEnabled()) {
			logger.debug("doFilter(ServletRequest, ServletResponse, FilterChain) - start"); //$NON-NLS-1$  
		}
		FilterInvocation fi = new FilterInvocation(request, response, chain);
		invoke(fi);
		if (logger.isDebugEnabled()) {
			logger.debug("doFilter(ServletRequest, ServletResponse, FilterChain) - end"); //$NON-NLS-1$  
		}
	}

	public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
		return this.securityMetadataSource;
	}

	@Override
	public Class<? extends Object> getSecureObjectClass() {
		// 下面的MyAccessDecisionManager的supports方面必须放回true,否则会提醒类型错误
		return FilterInvocation.class;
	}

	public void invoke(FilterInvocation fi) throws IOException,
			ServletException {
		InterceptorStatusToken token = super.beforeInvocation(fi);
		try {
			fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
		} finally {
			super.afterInvocation(token, null);
		}
	}
	
	private void initSystem(){
		List<PropertyFilter> filters = Lists.newArrayList();
		PropertyFilter filter = new PropertyFilter("EQB_enabled", "true");
		filters.add(filter);
		List<SystemEntity> data = systemService.getList(filters);
    	if (data!=null&&data.size()>0) {
    		
    		for (SystemEntity se : data) {
    			globalMap.put(se.getKey(), se.getValue());
				logger.debug("Initialize system configuration  key:={}-- value:={}",new Object[]{se.getKey(),se.getValue()});
			}
		}else{
			logger.warn("Not initialize system configuration");
		}
	}

	@Override
	public SecurityMetadataSource obtainSecurityMetadataSource() {
		return this.securityMetadataSource;
	}

	public void setSecurityMetadataSource(
			FilterInvocationSecurityMetadataSource securityMetadataSource) {
		this.securityMetadataSource = securityMetadataSource;
	}

	public void destroy() {

	}

	public void init(FilterConfig filterconfig) throws ServletException {

	}

	@Autowired
	public void setSystemService(SystemService systemService) {
		this.systemService = systemService;
	}

	
	
}
